package com.example.springboot.wechat.wechatinterface.controller;


import com.example.springboot.wechat.wechatinterface.job.TokenCache;
import com.example.springboot.wechat.wechatinterface.util.GsonUtils;
import com.example.springboot.wechat.wechatinterface.util.HttpClientUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 微信公众号请求地址url, 返回一个查询结果对象
 * @Project: SC
 * @Author: jinke
 * @Date 2018-05-10
 */
@Controller
@RequestMapping("/wechatHttpRequest")
public class WeChatHttpRequest {
    private static Log log = LogFactory.getLog(WeChatHttpRequest.class);

    @Autowired
    TokenCache tokenCache;

    /**
     * 根据code获取用户基本信息
     *
     * @param code
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryObj.do", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json;charset=UTF-8")
    public Map<String, Object> queryWechatHttpRequest(String code) {

        Map<String, Object> map = new HashMap<String, Object>();
        try {
            map = getOpenID(code.toString());
            if (map.containsKey("openid")) {
                Object access_token = map.get("access_token");
                Object openid = map.get("openid");
                map = getObj(access_token.toString(), openid.toString());
            }
            log.info("根据code获取用户基本信息： " + map.toString());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询参数不存在" + e);
        }
        return map;
    }

    /**
     * 根据重定向url查询Code
     *
     * @param redirect_uri
     * @return
     * @throws Exception
     */
    public static Map<String, Object> getCode(String redirect_uri) throws Exception {
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxb3882809e6c2f6fb&redirect_uri=" + redirect_uri + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
        String res = HttpClientUtils.get(url);
        Map<String, Object> map = GsonUtils.fromJson(res, Map.class);
        log.info("getCode-->根据重定向url查询Code：" + map.toString());
        return map;
    }

    /**
     * 根据code查询openid
     *
     * @param code
     * @return
     * @throws Exception
     */
    public static Map<String, Object> getOpenID(String code) throws Exception {
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxb3882809e6c2f6fb&secret=d8e3a9da06cd6c71959cd9033e43dd6c&code=" + code + "&grant_type=authorization_code";
        String res = HttpClientUtils.get(url);
        log.info("根据code查询openid结果： " + res.toString());
        Map<String, Object> map = GsonUtils.fromJson(res, Map.class);
        log.info("getOpenID-->根据code查询openid：" + map.toString());
        return map;
    }

    /**
     * 返回查询对象
     *
     * @param access_token
     * @param openid
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/getObj.do", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json;charset=UTF-8")
    public static Map<String, Object> getObj(String access_token, String openid) throws Exception {
        String url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openid + "&lang=zh_CN";

        HttpURLConnection httpConn = null;
        BufferedReader in = null;
        Map<String, Object> map = new HashMap<String, Object>();
        try {
                URL url1 = new URL(url);
                httpConn = (HttpURLConnection) url1.openConnection();
            log.info("httpConn打开连接： " + url1.toString());
                // 读取响应
                if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                StringBuffer content = new StringBuffer();
                String tempStr = "";
                in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(),"UTF-8"));
                while ((tempStr = in.readLine()) != null) {
                   content.append(tempStr);
                }
                    log.info("打印content信息： " + content.toString());
                     map = GsonUtils.fromJson(content.toString(), Map.class);
                   return map;
                } else {
                   throw new Exception("请求出现了问题!");}
                } catch (IOException e) {
                e.printStackTrace();
                } finally {
                in.close();
                httpConn.disconnect();
                }

//        String res = HttpClientUtils.get(url);
//        log.info("获取用基本信息结果： " + res.toString());
//        res = new String(res.getBytes("utf-8"), "UTF-8");
//        log.info("获取用基本信息编码UTF-8结果： " + res.toString());
//        Map<String, Object> map = GsonUtils.fromJson(res, Map.class);
//        log.info("获取用基本信息,返回查询对象：" + map.toString());
        return map;
    }


    @ResponseBody
    @RequestMapping(value = "/queryPath.do", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json;charset=UTF-8")
    public String queryPath(String media_id,String mediaFileUrl) {
        StringBuffer resultStr = null;
        String access_token = tokenCache.getCache("access_token");
        String url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token="+access_token+"&media_id="+media_id+ "&lang=zh_CN";
//        Map<String, Object> map = new HashMap<String, Object>();
//        Map<String, Object> resmap = new HashMap<String, Object>();
//        Map<String, String> mapStr = new HashMap<String, String>();
        URL url1 = null;
        URL mediaUrl;
        try {
            url1 = new URL(url);
            HttpURLConnection urlConn = (HttpURLConnection) url1.openConnection();
            //让输入输出流开启
            urlConn.setDoInput(true);
            urlConn.setDoOutput(true);
            //使用post方式请求的时候必须关闭缓存
            urlConn.setUseCaches(false);
            //设置请求头的Content-Type属性
            urlConn.setRequestProperty("Content-Type", "multipart/form-data;");
            urlConn.setRequestMethod("POST");
            //获取输出流，使用输出流拼接请求体
            OutputStream out = urlConn.getOutputStream();

            //读取文件的数据,构建一个GET请求，然后读取指定地址中的数据
            mediaUrl = new URL(mediaFileUrl);
            HttpURLConnection mediaConn = (HttpURLConnection)mediaUrl.openConnection();
            //设置请求方式
            mediaConn.setRequestMethod("GET");
            //设置可以打开输入流
            mediaConn.setDoInput(true);
            //获取传输的数据类型
            String contentType = mediaConn.getHeaderField("Content-Type");
            log.info("传输的数据类型为"+contentType);
            //将获取大到的类型转换成扩展名
            String fileExt = judgeType(contentType);
            log.info("文件的拓展名为"+fileExt);
            //获取输入流，从mediaURL里面读取数据
            InputStream in = mediaConn.getInputStream();
            BufferedInputStream bufferedIn = new BufferedInputStream(in);
            //数据读取到这个数组里面
            byte[] bytes = new byte[1024];
            int size = 0;
            //使用outputStream流输出信息到请求体当中去
            out.write(("----\r\n").getBytes());
            out.write(("Content-Disposition: form-data; name=\"media\";\r\n"
                    + "filename=\""+(new Date().getTime())+fileExt+"\"\r\n"
                    + "Content-Type: "+contentType+"\r\n\r\n").getBytes());
            while( (size = bufferedIn.read(bytes)) != -1) {
                out.write(bytes, 0, size);
            }

            //切记，这里的换行符不能少，否则将会报41005错误
            out.write(("\r\n----\r\n").getBytes());

            bufferedIn.close();
            in.close();
            mediaConn.disconnect();

            InputStream resultIn = urlConn.getInputStream();
            InputStreamReader reader = new InputStreamReader(resultIn);
            BufferedReader bufferedReader = new BufferedReader(reader);
            String tempStr = null;
            resultStr = new StringBuffer();
            while((tempStr = bufferedReader.readLine()) != null) {
                resultStr.append(tempStr);
            }

            bufferedReader.close();
            reader.close();
            resultIn.close();
            urlConn.disconnect();
//            String res = HttpClientUtils.get(url);
//
//            log.info("获取微信接口路径结果： " + res.toString());
//            res = new String(res.getBytes("utf-8"), "UTF-8");
//            log.info("获取用基本信息编码UTF-8结果： " + res.toString());
//            map = GsonUtils.fromJson(res, Map.class);
            log.info("根据media_id获取queryPath结果： " + resultStr.toString());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("queryPath查询参数不存在" + e);
        }
        return resultStr.toString();
    }
    /**
     * 通过传过来的contentType判断是哪一种类型
     * @param contentType 获取来自连接的contentType
     * @return
     */
    public static String judgeType(String contentType) {
        String fileExt = "";
        if("image/jpeg".equals(contentType)) {
            fileExt = ".jpg";
        } else if("audio/mpeg".equals(contentType)) {
            fileExt = ".mp3";
        } else if("audio/amr".equals(contentType)) {
            fileExt = ".amr";
        } else if("video/mp4".equals(contentType)) {
            fileExt = ".mp4";
        } else if("video/mpeg4".equals(contentType)) {
            fileExt = ".mp4";
        }
        return fileExt;
    }

}
